package com.snowyee.snowyeecodesandbox.service.impl;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeRequest;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeResponse;
import com.snowyee.snowyeecodesandbox.model.ExecuteMessage;
import com.snowyee.snowyeecodesandbox.model.JudgeInfo;
import com.snowyee.snowyeecodesandbox.service.CodeSandbox;
import com.snowyee.snowyeecodesandbox.utils.ProcessUtils;
import org.springframework.stereotype.Service;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class DockerCodeSandboxImplOld implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final Boolean FIRST_INIT = false;

    private static final Long TIME_OUT = 5000L;


    /**
     * 测试沙箱方法
     * @param args
     */
    public static void main(String[] args) {
        DockerCodeSandboxImplOld javaCodeSandbox = new DockerCodeSandboxImplOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2","3 4"));
        String code = ResourceUtil.readStr("testCode/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCodeInteraction/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);

    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

//        System.setSecurityManager(new DenySecurityManager());
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 1、把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        // File.separator是为了兼容不同操作系统
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;

        // 判断全局代码目录是否存在，不存在则新建
        if (!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }

        // 用户存放的代码进行隔离
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        System.out.println(userCodeFile.getAbsolutePath());
        // 2、编译代码得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        ExecuteMessage compileMessage = ProcessUtils.getProcessMessage(compileCmd,"编译");
        System.out.println(compileMessage);

        // 3、创建容器，把文件复制到容器内，同时搜集时间和内存占用等信息
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String images = "openjdk:8-alpine";
        if (FIRST_INIT){
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(images);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item){
                    System.out.println("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
            System.out.println("下载完成");
        }

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(images);
        // 限制容器的配置
        HostConfig hostConfig = new HostConfig();
        // 限制内存最大只能使用100M
        hostConfig.withMemory(100*100*1000L);
        // 限制不让把信息从内存写到硬盘
        hostConfig.withMemorySwap(0L);
        // 限制CPU最多使用1核
        hostConfig.withCpuCount(1L);
        // 具体限制一个一个的权限
//        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置的字符串"));
        // 把数据挂载到/app目录下
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                // 限制不让使用网络
                .withNetworkDisabled(true)
                // 限制根目录只读，不可写
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();

        // 4、启动容器，执行代码
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs :inputList){
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            // docker exec eloquent_goodall java -cp /app Main 1 3
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errormessage = {null};
            long time = 0L;
            // 判断是否超时
            final boolean[] timeout = {true};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(){

                @Override
                public void onNext(Frame frame){
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)){
                        errormessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errormessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }

                // 程序结束时执行这个
                @Override
                public void onComplete() {
                    timeout[0] = false;
                    super.onComplete();
                }
            };

            final long[] maxMemory = {0L};
            // 获取占用内存信息
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onComplete(){

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onError(Throwable throwable) {

                }


                @Override
                public void close() throws IOException {

                }
            });

            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        // 控制程序是否超时
                        // TIME_OUT, TimeUnit.MICROSECONDS形参
                        .awaitCompletion();
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }

            executeMessage.setErrorMessage(errormessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }


        // 5、收集整理的输出结果
        // 判断运行时间是否超时
        long maxTime = 0;
        long maxMemory = 0;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessageList){
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                // 表示运行错误，比如程序运行失败的信息
                executeCodeResponse.setStatus("3");
                break;
            }
            long time = executeMessage.getTime();
            if (time > maxTime){
                maxTime = time;
            }
            // 正常运行完成
            executeCodeResponse.setStatus("1");
            // 6、错误处理，提成程序的健壮性
            if (executeMessage.getStatus() != null && executeMessage.getStatus() == 2){
                // 沙箱错误，可能是编译出现错误
                executeCodeResponse.setStatus("2");
            }

            outputList.add(executeMessage.getMessage());
            maxMemory = executeMessage.getMemory();
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        // 获取最大运行时间
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 6、删除临时文件
        if (userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除"+(del?"成功":"失败"));
        }

        return executeCodeResponse;
    }


}
